<?php
// a way to prevent someone from loading this page directly?
// @header("location: index.php") and exit();
class PicturesController extends AppController 
{    
	/*
	 * Attributes
	 */		

   

	/*
	 * Methods
	 */	

	// called when no action is passed to this controller (default action)		
	function index($id = null) 
	{
		$this->Picture->ID = $id;
		$this->set('picture', $this->Picture->read(NULL, $id));
	}

	function upload($event_id = null, $event_page = 0) 
	{
		if ($event_id == null) 
		{
			// redirect to an error page
			$this->Session->setFlash("To upload a picture, you must add it to some event; we didn't get an event ID.");
			$this->redirect("/events/");
		}
		else 
		{	
			// verify that the user is logged in before saving uploaded files
			// if ($this->Auth->User('id') != null) 
			// {
			//		redirect if not logged in	
			// }
			
			// we need to run verification that the user is authorized to post to the chosen event
			// ...
			
			/* Initial variables */
			
			// destination for uploaded files
			$pix_event_dir = WWW_ROOT . "pix" . DS . $event_id;		// DS == DIRECTORY_SEPARATOR
			
			// user
			$person_id = $this->Auth->User('id');
	
			// time, for "create" and "modify" attributes 
			$now = date("Y-m-d H:i:s");
			
			// parameters from the file POST
			$chunk = isset($_POST["chunk"]) ? $_POST["chunk"] : 0;
			$chunks = isset($_POST["chunks"]) ? $_POST["chunks"] : 0;
			$file_name = isset($_POST["name"]) ? $_POST["name"] : '';
			
			
			/* Transform file name */
			
			// Clean the file_name for security and to eliminate spaces
			$file_name = preg_replace('/[^\w\._]+/', '', $file_name);
		
			$dot_position = strrpos($file_name, '.');
			$file_name_name = substr($file_name, 0, $dot_position);
			$file_name_ext = substr($file_name, $dot_position);
			
			// Make sure the file_name is unique (but only when not chunking)
			if ($chunks < 2 && file_exists($pix_event_dir . DS . $file_name)) 
			{
				$count = 1;
				while (file_exists($pix_event_dir . DS . $file_name_name . '_' . $count . $file_name_ext))
					$count++;
				
				// TODO: should we leave the extension off for now (hash on just the name part)?
				$file_name = $file_name_name . '_' . $count . $file_name_ext;
			}
			
			// Hash file_name and produce a 23-character time-based "unique" id (not a UUID)
			$uid = uniqid(sha1($file_name), true);
			
			// Look for the content type header
			if (isset($_SERVER["HTTP_CONTENT_TYPE"]))
				$mime_type = $_SERVER["HTTP_CONTENT_TYPE"];
			if (isset($_SERVER["CONTENT_TYPE"]))
				$mime_type = $_SERVER["CONTENT_TYPE"];
			
			// TODO: add image mime-type functionality (recognition, filtering)
			// Are we doing anything that will break on, say, a TIFF image?
			
			//if ($this->data['Picture']['file_type'] == 'image/jpeg') {
			//	$ext = 'jpg';
			//}
			//if ($this->data['Picture']['file_type'] == 'image/png') {
			//	$ext = 'png';
			//}
			
			$new_file_name = $uid . $file_name_ext;
			
			
			/* Verify destination directory */
			
			// Create event dir if necessary
			if (!file_exists($pix_event_dir))
				@mkdir($pix_event_dir);
			
			// verify directory exists and can be opened
			if (is_dir($pix_event_dir) && ($dir = opendir($pix_event_dir))) 
			{
				closedir($dir);
			} 
			else
				exit("Upload failed: couldn't open event pix directory.");
			
			
			/* Save file */
			
			// Handle multipart uploads (older WebKit versions didn't support multipart in HTML5)
			if (strpos($mime_type, "multipart") !== false) 
			{
				// TODO:  shouldn't we be doing this test for ALL uploads?
				if (isset($_FILES['file']['tmp_name']) && is_uploaded_file($_FILES['file']['tmp_name'])) 
				{
					// Open temp file
					$out = fopen($pix_event_dir . DS . $new_file_name, $chunk == 0 ? "wb" : "ab");
					if ($out) 
					{
						// Read binary input stream and append it to temp file
						$in = fopen($_FILES['file']['tmp_name'], "rb");
		
						if ($in) 
						{
							while ($buff = fread($in, 4096))
								fwrite($out, $buff);
						} 
						else
							exit("Upload failed: couldn't open input stream.");
							
						fclose($in);
						fclose($out);
						// delete the temp file [why are errors suppressed?]
						@unlink($_FILES['file']['tmp_name']);
					} 
					else
						exit("Upload failed: couldn't open output stream.");
				} 
				else
					exit("Upload failed: couldn't find uploaded file.");
			} 
			// Handle non-multipart uploads
			else 
			{
				// Open temp file
				$out = fopen($pix_event_dir . DS . $new_file_name, $chunk == 0 ? "wb" : "ab");
				if ($out) 
				{
					// Read binary input stream and append it to temp file
					$in = fopen("php://input", "rb");
					
					if ($in) 
					{
						while ($buff = fread($in, 4096))
							fwrite($out, $buff);
					} 
					else
						exit("Upload failed: couldn't open input stream.");
					
					fclose($in);
					fclose($out);
				} 
				else
					exit("Upload failed: couldn't open output stream.");
			}
			
			$file_size = filesize($pix_event_dir . DS . $new_file_name);
			
			
			/* Add to SFP database */
			
			// insert record in database
			$this->Picture->query("INSERT INTO `pictures` (`event_id`, `person_id`, `file_name`, `file_type`, `file_size`, `modified`, `created`) " . "VALUES ($event_id, $person_id, '$new_file_name', '$mime_type' , $file_size, '$now', '$now')");
			
			
			// $this->redirect("/events/view/$event_id/$event_page");
		}

	}

	function upload_finished($event_id = null, $event_page = 0) 
	{
		if ($event_id == null) 
		{
			// redirect to an error page
			$this->Session->setFlash("To upload a picture, you must add it to some event; we didn't get an event ID.");
			$this->redirect("/events/");
		}
		else 
			$this->redirect("/events/view/event:$event_id/page:$event_page");
	}
	
	function delete($pid) {
	    // Track down the filename of the picture
	    $pic = $this->Picture->find('first', array('conditions' => array('id' => $pid)));
	    
	    if (empty($pic)) {
	        // For some reason, the given picture is not in the database...
	        return;
	    }
	    
	    $filename = $pic['Picture']['file_name'];
	    $event = $pic['Picture']['event_id'];
	
	    $this->Picture->deleteAll(array("Picture.id" => $pid));
	    
	    // Delete physical file only after it has been removed from db
	    $file_location = WWW_ROOT . "pix" . DS . $event . DS . $filename;
	    unlink($file_location);
	   
	    
	    $this->Session->setFlash("Photo deleted");
	    $this->redirect($this->referer());
	}
	
	function edit(){
		if($this->Picture->save(filter_var_array($this->data,FILTER_SANITIZE_STRING))){
			$captionArr = $this->Picture->find('first', array('conditions' => array('id' => $this->data['Picture']['id'])));
			$caption = $captionArr['Picture']['caption'];
			$this->set('caption', $caption);
			$this->render('edit', 'ajax');
		}
	}
}
?>
